#include <mboot.h>
#include <common.h>
#include <elf.h>

extern elf_t kernel_elf;

void print_stack_trace(unsigned int ebp2)
{

	unsigned int *ebp, *eip;
	if(ebp2)
		ebp = (unsigned int *)ebp2;
	else
		asm volatile ("mov %%ebp, %0" : "=r" (ebp));
	eip = ebp+1;
	while(*eip)
	{
	if(elf_lookup(*eip,&kernel_elf))
		printf("\n[%x] %s", *eip, elf_lookup(*eip,&kernel_elf));
	else
		printf("\n[%x]");
		ebp = (unsigned int *) *ebp;
		eip = ebp+1;
	}
}

char *panic_lookup(unsigned int eip)
{
	if(eip>0xC0000000)
		return elf_lookup(eip,&kernel_elf);
	else
	return 0;
}

void panic(char *msg)
{
	printf("\n*** System panic: %s ***\n", msg);
	print_stack_trace(0);
	for(;;);
}

void print_stack()
{
	unsigned int *esp;
	asm volatile ("mov %%esp, %0" : "=r" (esp));
	while(*esp)
	{
		printf("%x:[%x] : %s \n",esp,*esp,panic_lookup(*esp));
		esp++;
	}
}
